package com.wlit.alarm;

import com.wlit.alarm.service.AlarmServiceImpl;
import com.wlit.alarm.service.IAlarmService;
import com.wlit.alarm.utils.CommPortUtils;
import com.wlit.alarm.utils.SmsUtils;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.List;

/**
 * 主界面
 */
public class MainFrame extends javax.swing.JFrame  {


    private final Logger logger = Logger.getLogger(MainFrame.class);
    private final JDesktopPane desktopPane_1 = new JDesktopPane();
    private final JLabel label_port = new JLabel();
    private final JButton bt_open = new JButton();
    private final JButton bt_close = new JButton();
    private final JButton bt_check = new JButton();
    private final JButton bt_reset = new JButton();
    private final JTextArea content_area = new JTextArea();
    private final JTextArea config_area = new JTextArea();
    private final JLabel label_phone_number = new JLabel();
    private final JTextField phone_number = new JTextField();
    private final JButton bt_sms_test = new JButton();
    private final JButton bt_call_test = new JButton();
    private final JComboBox comboBox_port = new JComboBox();
    private final List<String> comList = new ArrayList<>();
    private IAlarmService alarmService = new AlarmServiceImpl(this);

    public MainFrame() {
    }

    public void initGUI() {
        Properties prop = new Properties();
        try {
            prop.load(new FileInputStream("config.properties"));
            if (prop!=null && prop.containsKey("com")){
                String com = prop.getProperty("com");
                comboBox_port.setSelectedItem(com);
                innerOpenListen(com);
            }
        }catch(Exception e){
            logger.error("加载配置文件失败", e);
        }

        setTitle("为乐短信电话报警器");
        getContentPane().setLayout(null);
        setResizable(false);
        setBounds(100, 100, 600, 600);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        getContentPane().add(desktopPane_1);
        desktopPane_1.setLayout(null);
        desktopPane_1.setBounds(153, 305, 287, -228);

        label_port.setBounds(23, 15, 40, 30);
        getContentPane().add(label_port);
        label_port.setText("串口:");

        //初始化窗口
        CommPortUtils.initComports(comList);
        Collections.reverse(comList);
        for (String curr : comList) {
            comboBox_port.addItem(curr);
        }
        //串口
        comboBox_port.setBounds(70, 15, 86, 30);
        getContentPane().add(comboBox_port);

        bt_open.setBounds(170, 15, 88, 30);
        bt_open.setText("打开串口");
        bt_open.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openListen(e);
            }
        });
        getContentPane().add(bt_open);

        bt_close.setBounds(260, 15, 88, 30);
        bt_close.setText("关闭串口");
        bt_close.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                closeListen();
            }
        });
        getContentPane().add(bt_close);

        bt_check.setBounds(360, 15, 88, 30);
        bt_check.setText("检查端口");
        bt_check.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chechCommAvail();
            }
        });
        getContentPane().add(bt_check);

        bt_reset.setBounds(460, 15, 88, 30);
        bt_reset.setText("重启硬件");
        bt_reset.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                restartHardware();
            }
        });
        getContentPane().add(bt_reset);

        label_phone_number.setBounds(20, 60, 80, 30);
        label_phone_number.setText("手机号码:");
        getContentPane().add(label_phone_number);

        phone_number.setBounds(80, 60, 120, 30);
        phone_number.setText("");
        getContentPane().add(phone_number);

        bt_sms_test.setBounds(220, 60, 88, 30);
        bt_sms_test.setText("短信测试");
        bt_sms_test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                 testSendSMS(e);
            }
        });
        getContentPane().add(bt_sms_test);

        bt_call_test.setBounds(320, 60, 88, 30);
        bt_call_test.setText("电话测试");
        bt_call_test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                testVoiceCall(e);
            }
        });
        getContentPane().add(bt_call_test);

        content_area.setBounds(20, 120, 500, 160);
        getContentPane().add(content_area);

        config_area.setBounds(20, 320, 500, 160);
        config_area.setText("为乐短信电话报警服务器: http://127.0.0.1:"+Main.HTTP_PORT+"/"
                +"\r\n使用方法: 1、选择串口。2、打开串口。"
                +"\r\n验证功能是否可用：输入手机号码，点击短信测试或者电话测试。"
        );

        getContentPane().add(config_area);

        try {
            this.setIconImage(ImageIO.read(getClass().getResourceAsStream("/icon.jpeg")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
            setToolSystemTray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public IAlarmService getAlarmService() {
        return alarmService;
    }

    private void testSendSMS(ActionEvent e){
        String phoneNumber = phone_number.getText().trim();
        if (phoneNumber.length() == 0) {
            JOptionPane.showMessageDialog(this, "请输入手机号码", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (phoneNumber.length() != 11) {
            JOptionPane.showMessageDialog(this, "请填写11位手机号码", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String content = "广州为乐信息科技提醒你,温度出现异常了！";
        byte[] bytes1 = SmsUtils.buildSms(phoneNumber,content,4);
        alarmService.send(bytes1);
    }

    private void testVoiceCall(ActionEvent e){
        String phoneNumber = phone_number.getText().trim();
        if (phoneNumber.length() == 0) {
            JOptionPane.showMessageDialog(this, "请输入手机号码", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (phoneNumber.length() != 11) {
            JOptionPane.showMessageDialog(this, "请填写11位手机号码", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String content = "广州为乐信息科技提醒你,温度出现异常了！";
//        byte[] bytes1 = SmsUtils.buildSms(phoneNumber,content,4);
//        alarmService.send(bytes1);

        byte[] bytes2 = SmsUtils.buildVoice(phoneNumber,content);
        alarmService.send(bytes2);
    }

    private void openListen(ActionEvent e) {
        String com = (String) comboBox_port.getSelectedItem();
        System.out.println(">>>" + com);

        innerOpenListen(com);
    }

    private void innerOpenListen(String com) {
        alarmService.open(com);

        if (alarmService.isOpen()) {
            bt_open.setEnabled(false);
            bt_close.setEnabled(true);
            bt_reset.setEnabled(true);
            bt_check.setEnabled(false);
            //打开端口才启动连接后台
            content_area.setText("打开串口成功" + com);

            Properties prop = new Properties();
            prop.setProperty("com", com);
            try {
                prop.store(new FileOutputStream("config.properties"), "SerialPort");
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            content_area.setText("打开串口失败" + com);
        }
    }

    private void closeListen() {
        if (alarmService != null) {
            alarmService.close();
        }
        content_area.setText("关闭串口");
        bt_open.setEnabled(true);
        bt_close.setEnabled(false);
        bt_reset.setEnabled(false);
        bt_check.setEnabled(true);
    }

    private void chechCommAvail() {
        List<String> listPortAvail = CommPortUtils.testCommAvail();
        if (listPortAvail.size() > 0) {
            StringJoiner stringJoiner = new StringJoiner(",");
            for (String curr : listPortAvail) {
                stringJoiner.add(curr);
            }
            content_area.setText("有效串口:" + stringJoiner);
            //修改有效串口
            comboBox_port.setSelectedItem(listPortAvail.get(0));
        } else {
            content_area.setText("没有有效的串口，请检测设备管理器");
        }
    }

    /**
     * 重启硬件
     */
    private void restartHardware() {
        byte[] bytes = SmsUtils.buildReset();
        alarmService.send(bytes);
    }


    /**
     * 添加信息
     * @param data
     */
    public void showInfo(String data) {
        logger.info("信息:" + data);
        content_area.setText(data);
    }

    protected void setToolSystemTray() throws Exception {
        // 系统是否支持系统托盘
        if (SystemTray.isSupported()) {

            // 获取SystemTray系统托盘实例
            SystemTray tray = SystemTray.getSystemTray();

            // 弹出式 菜单
            PopupMenu popup = new PopupMenu();

            // 创建关于菜单项
            MenuItem aboutItem = new MenuItem("Open");
            aboutItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(true);
                }

            });
            popup.add(aboutItem);

            // 创建退出菜单项
            MenuItem exitItem = new MenuItem("Exit");
            exitItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    //@todo 要做哪些退出呢
                    alarmService.close();
                    dispose();
                    System.exit(0);
                }
            });
            popup.add(exitItem);
            // 构造托盘图标
//            String icon = MainFrame.class.getResource("/icon.jpeg").getFile();
//            ImageIcon imageIcon = new ImageIcon(icon);
            Image image = null;
            try {
                image = ImageIO.read(getClass().getResourceAsStream("/icon.jpeg"));
            } catch (Exception ex) {
                String icon = MainFrame.class.getResource("/icon.jpeg").getFile();
                ImageIcon imageIcon = new ImageIcon(icon);
                image = imageIcon.getImage();
            }
            TrayIcon trayIcon = new TrayIcon(image, "为乐短信电话报警器", popup);

            trayIcon.setImageAutoSize(true);
            // 鼠标事件
            trayIcon.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {
                    // 单击显示窗口
                    if (e.getClickCount() == 1) {
                        setVisible(true);
                    }
                }
            });

            // 添加托盘图标
            try {
                tray.add(trayIcon);
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
        } else {
            JOptionPane.showMessageDialog(null,
                    System.getProperty("os.version") + "系统不支持系统托盘!");
        }
    }

}
